<template>
	<div class="message-container" ref="messageContainer">
		<MessageArea
			title="留言板"
			:subTitle="`(${datas.total})`"
			:isListLoading="isLoading"
			:list="datas.rows"
			@submited="handleSubmit"
		/>
	</div>
</template>

<script>
import MessageArea from "@/components/MessageArea";
import fetchDatas from "@/mixins/fetchDatas";
import * as msgApi from "@/api/message";
import mainScroll from "@/mixins/mainScroll";
import eventBus from "@/eventBus.js";
export default {
	components: {
		MessageArea,
	},
	mixins: [mainScroll("messageContainer"), fetchDatas({ total: 0, rows: [] })],
	data() {
		return {
			page: 1,
			limit: 10,
		};
	},

	computed: {
		hasMore() {
			return this.datas.rows.length < this.datas.total;
		},
	},
	mounted() {
		eventBus.$on("mainScroll", this.handleMainScroll);
	},
	beforeDestroy() {
		eventBus.$off("mainScroll", this.handleMainScroll);
	},

	methods: {
		async fetchData() {
			return msgApi.getMessages(this.page, this.limit);
		},
		//加载更多评论
		async fetchMore() {
			if (!this.hasMore) {
				//已经加载完全部评论
				return;
			}
			//加载下一页
			this.page++;
			this.isLoading = true;
			const resp = await this.fetchData();
			//将获取的数据连接在原始数据的后面
			this.datas.rows = this.datas.rows.concat(resp.rows);
			this.datas.total = resp.total;
			this.isLoading = false;
		},

		//dom为当前的容器message-container
		handleMainScroll(dom) {
			if (this.isLoading || !dom) {
				//正在加载中或当前dom不存在
				return;
			}
			const range = 50;
			const gap = Math.abs(dom.scrollTop + dom.clientHeight - dom.scrollHeight);
			if (gap < range) {
				this.fetchMore();
			}
		},
		async handleSubmit(formData, callback) {
			const result = await msgApi.postMessage(formData);
			this.datas.rows.unshift(result);
			this.datas.total++;
			callback("评论成功");
		},
	},
};
</script>

<style scoped>
.message-container {
	position: relative;
	width: 100%;
	height: 100%;
	overflow-y: auto;
	padding: 25px 0;
	box-sizing: border-box;
	scroll-behavior: smooth;
}
.message-area-container {
	width: 700px;
	margin: 0 auto;
}
</style>
